import React, { memo, useEffect, useState } from 'react';
import axios from 'axios';
import { Checkbox, TreeSelect } from 'antd';
import './index.less';

const { TreeNode } = TreeSelect;

function EyesTreeSelect({ value, onChange }) {
  const [selectedStatus, setSelectedStatus] = useState(false);
  const [treeList, setTreeList] = useState([]);
  const [ready, setready] = useState(false);
  const [selectValue, setSelectValue] = useState('');

  // 获取下拉数据
  const getDataList = () => {
    axios({
      method: 'get',
      url: '/api/cityeyes/vfp/openapi/video/v1/subject-tree?subjectCode=10002',
    })
      .then(({ data }) => {
        if (data.code === 200) {
          if (data.data && data.data.children && data.data.children.length !== 0) {
            setTreeList(data.data.children);
          }
        }
      })
      .catch(() => {
        onChange('-1');
      });
  };

  // 渲染下拉节点
  const treeNodeRender = (renderList) => {
    if (!renderList || renderList.length === 0) {
      return;
    }
    return renderList.map((v) => (
      <TreeNode disableCheckbox value={v.id} title={v.subjectName} key={v.id}>
        {v.children && treeNodeRender(v.children)}
      </TreeNode>
    ));
  };
  // 选择专题树
  const treeSelectOnChange = (newValue) => {
    if (newValue) {
      onChange(newValue);
    } else {
      onChange('-1');
    }
  };

  // 选择使用星眸
  const checkboxOnChange = (e) => {
    if (e.target.checked) {
      treeList.length === 0 && getDataList();
      setSelectedStatus(e.target.checked);
    } else {
      setSelectedStatus(false);
      setSelectValue('');
      onChange('-1');
    }
  };

  useEffect(() => {
    if (value && value !== '-1') {
      treeList.length === 0 && getDataList();
      setSelectedStatus(true);
      setSelectValue(value);
    } else {
      checkboxOnChange({ target: { checked: false } });
    }
    setTimeout(() => {
      const myDiv = document.getElementById('eyesTreeSelectDiv');
      if (!myDiv) {
        const popupContainer = document.createElement('div');
        popupContainer.id = 'eyesTreeSelectDiv';
        document.body.appendChild(popupContainer);
      }
      setready(true);
    });
  }, [value]);
  return (
    <div>
      <Checkbox checked={selectedStatus} onChange={checkboxOnChange}>
        视频来源于星眸
      </Checkbox>
      {ready && selectedStatus && (
        <TreeSelect
          style={{ width: '100%' }}
          value={selectValue}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          placeholder="请选择专题"
          getPopupContainer={() => document.getElementById('eyesTreeSelectDiv')}
          onChange={treeSelectOnChange}
        >
          {treeNodeRender(treeList)}
        </TreeSelect>
      )}
    </div>
  );
}
export default memo(EyesTreeSelect);
